import 'dart:convert';

import '../entity/palette_model.dart';
import '../utils/config_loader/palette_loader.dart';
import '../utils/db_utils.dart';

class PaletteService {
  /// 查询所有调色板
  static Future<List<PaletteModel>> queryAll() async {
    final db = await DbUtils.database;
    return await db.query('palette', orderBy: 'date_time desc').then((value) {
      return value.map((e) {
        PaletteModel paletteModel = PaletteLoader.load(e['data'] as String);
        paletteModel.id = e['id'] as int;
        return paletteModel;
      }).toList();
    });
  }

  /// 根据id查询调色板
  static Future<PaletteModel?> queryById(int id) async {
    final db = await DbUtils.database;
    return await db
        .query('palette', where: 'id = ?', whereArgs: [id], limit: 1)
        .then((value) {
          if (value.isNotEmpty) {
            var palette = PaletteModel.fromJson(
              jsonDecode(value.first['data'] as String),
            );
            palette.id = value.first['id'] as int;
            return palette;
          }
          return null;
        });
  }

  /// 根据id查询调色板
  static Future<PaletteModel?> queryLast() async {
    final db = await DbUtils.database;
    return await db.query('palette', orderBy: 'date_time desc', limit: 1).then((
      value,
    ) {
      if (value.isNotEmpty) {
        var palette = PaletteModel.fromJson(
          jsonDecode(value.first['data'] as String),
        );
        palette.id = value.first['id'] as int;
        palette.name = value.first['name'] as String;
        return palette;
      }
      return null;
    });
  }

  /// 保存调色板
  static insert(PaletteModel palette) async {
    final db = await DbUtils.database;
    int id = await db.insert('palette', {
      'data': jsonEncode(palette.toJson()),
      'name': palette.name,
      'date_time': DateTime.now().millisecondsSinceEpoch,
    });
    palette.id = id;
  }

  /// 更新调色板
  static updateById(PaletteModel palette) async {
    final db = await DbUtils.database;
    await db.update(
      'palette',
      {
        'data': jsonEncode(palette.toJson()),
        'name': palette.name,
        'date_time': DateTime.now().millisecondsSinceEpoch,
      },
      where: 'id = ?',
      whereArgs: [palette.id],
    );
  }

  /// 删除调色板
  static delete(int id) async {
    final db = await DbUtils.database;
    await db.delete('palette', where: 'id = ?', whereArgs: [id]);
  }

  /// 根据名称查询调色板
  static Future<PaletteModel?> queryByName(String name) async {
    final db = await DbUtils.database;
    return await db
        .query('palette', where: 'name = ?', whereArgs: [name], limit: 1)
        .then((value) {
          if (value.isNotEmpty) {
            var palette = PaletteModel.fromJson(
              jsonDecode(value.first['data'] as String),
            );
            palette.id = value.first['id'] as int;
            palette.name = value.first['name'] as String;
            return palette;
          }
          return null;
        });
  }

  /// 保存调色板
  static Future<int> saveOrUpdatePalette(PaletteModel paletteModel) async {
    var old = await PaletteService.queryByName(paletteModel.name);
    if (paletteModel.id == null || paletteModel.id == 0) {
      if (old != null) {
        paletteModel.name = (paletteModel.name + DateTime.now().toString());
      }
      await PaletteService.insert(paletteModel);
    } else {
      if (old != null && old.id != paletteModel.id) {
        paletteModel.name = (paletteModel.name + DateTime.now().toString());
      }
      await PaletteService.updateById(paletteModel);
    }
    return paletteModel.id!;
  }
}
